package com.boco.blch.analysiser.util;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.boco.blch.analysiser.exception.TagNotFoundException;

/**
 * 此类方法仅限于BOCO_ShellCommand_Execute服务返回的结果进行解析，无法通用，请注意
 * @author someone
 *
 */
public class XmlUtil {
	private static final String RESULT_STATUS_TAGNAME = "Result";
	private static final String RESULT_STATUS_SUCCESS = "Success";
	private static final String RESULT_STATUS_ERROR = "Error";
	private static final String RESULT_MESSAGE_TAGNAME = "CommandResult";
	
	/*查找Result标签体内的文本内容，当此标签体内的内容不是success或者error时抛出异常*/
	public static boolean isSuccess(String source) throws IllegalArgumentException{
		if(RESULT_STATUS_SUCCESS.equalsIgnoreCase(getTextByTag(source, RESULT_STATUS_TAGNAME)))
			return true;
		if(RESULT_STATUS_ERROR.equalsIgnoreCase(getTextByTag(source, RESULT_STATUS_TAGNAME)))
			return false;
		throw new IllegalArgumentException("数据格式不正确，请检查！");
	}
	
	/*查找CommandResult标签体内的文本内容，当无此标签时抛出异常。请确认isSuccess返回true时再调用此方法，否则会抛出异常*/
	public static String getMessageFromResult(String source) throws TagNotFoundException{
		String message = null;
		message = getTextByTag(source, RESULT_MESSAGE_TAGNAME);
		if(message == null)
			throw new TagNotFoundException("数据中不包含结果体标签，请检查！");
		return message;
	}
	
	
	/*请保证要查找的标签名称唯一*/
	public static String getTextByTag(String source, String tagName){
		Document doc = Jsoup.parseBodyFragment(source);
		Element body = doc.body();
		Elements eles = body.getElementsByTag(tagName);
		if(eles.size() != 0){
			return eles.first().text();
		}
		return null;
	}
	
	public static String getTextByTag(String source, String tagName, int index){
		Document doc = Jsoup.parseBodyFragment(source);
		Element body = doc.body();
		Elements eles = body.getElementsByTag(tagName);
		if(eles.size() != 0){
			try{
				Elements resultlist = eles.eq(index);
				return resultlist.first().text();
			}catch(Exception e){
				return null;
			}
		}
		return null;
	}
	
	/**
	 * 根据name标签的text，找到对应的value标签的text
	 * (如果同一层级内的标签，有某个标签的text为指定值，那么返回他的第一个兄弟节点的text)
	 * @param source 查找的源
	 * @param nameText name标签中的值
	 * @return
	 */
	public static String getValueByName(String source, String nameText){
		Document doc = Jsoup.parseBodyFragment(source);
		Element body = doc.body();
		try{
			Elements nameNodes = body.getElementsMatchingOwnText(nameText);
			for (int i = 0; i <= nameNodes.size(); i++){
				Element nameNode = nameNodes.get(i);
				if(nameNode.text().equals(nameText)){
					Element valueNode = nameNode.siblingElements().get(0);
					return valueNode.text();
				}
			} 
			return "";
		} catch (Exception e){
			return "";
		}
	}
	
	

}
